<template>
    <Row type="flex" justify="space-around" class="code-row-bg">
        <Spin fix v-if="formLoading">
            <Icon type="ios-loading" size=18 class="demo-spin-icon-load"></Icon>
            <div>Loading</div>
        </Spin>
        <Form ref="selfCheckForm" :model="dataClone" :rules="ruleCustom" class="self-check-form w" label-position='top'
              :show-message="false">
            <Row type="flex" justify="space-around" class="code-row-bg">
                <Col span="11">
                    <FormItem label="二级集团：" prop="belongOrgId">
                        <Input class="w" v-model="dataClone.belongOrgName" readonly></Input>
                        <!--<Select class='w' placeholder="集团名称"  v-model='dataClone.belongOrgId' label-in-value @on-change="belongChange">-->
                            <!--<Option v-for="item in twoLevel" :value="item.orgId" :key="item.orgId">{{item.orgName}}</Option>-->
                        <!--</Select>-->
                    </FormItem>
                </Col>
                <Col span="11" >
                    <FormItem label="年度：" prop="year" >
                        <Input placeholder="请输入" class="w" v-model="dataClone.year" readonly></Input>
                    </FormItem>
                </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
                <Col span="11">
                <FormItem label="企业名称：" prop="companyId">
                    <!--<Input v-model="dataClone.companyName" type="text" readonly></Input>-->
                    <cascaderDom class="query-form-el" ref="companyQuery" :orgTree="true"
                                 :currentOrgId = "dataClone.companyId" style="width: 100%" :rootOrgId="dataClone.belongOrgId"
                                 :setCurrentName="{label:dataClone.companyName, value:dataClone.companyId}"
                                 @setOrgInfo='(data)=>{ if (data && data instanceof Array && data.length > 0 ) {this.$set(this.dataClone, "companyId", data[data.length - 1])}}'
                                 @setOrgname='(data)=>{ if(data){this.$set(this.dataClone, "companyName", data)}}'></cascaderDom>
                </FormItem>
                </Col>
                <Col span="11">
                    <FormItem label="自评时间：" prop="selfLevelTime">
                    <DatePicker type="date" placeholder="选择日期" class='w' v-model="dataClone.selfLevelTime" :clearable="false"
                                disabled :options="{disabledDate(date) {return date && date.valueOf() > new Date();}}"></DatePicker>
                </FormItem>
                </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
                <Col span="11">
                <FormItem label="企业负责人：" prop="manager">
                    <userDom ref="userDom" :selectData='setCurrentUserName' :placeholderStr="'请选择企业负责人'"
                             :singleChoice=true :ifUser="true" :rootOrgName="currentUser.companyName"
                             @setData = '(data)=>{ if(data){this.$set(dataClone, "manager", data.userId),this.$set(dataClone, "managerName", data.userName)}}'></userDom>
                </FormItem>
                </Col>
                <Col span="11">
                    <FormItem label="行业分类：" prop="industryName">
                        <Select multiple placeholder="请选择行业分类后点击刷新"  v-model='dataClone.industryName'>
                            <!--<Option v-for="item in dictMap['env-00006']" :value="item.codingCodeId" :key="item.codingCodeId" >{{ item.codingName }}</Option>-->
                            <Option v-for="item in industryNames" :value="item" :key="item">{{item}}</Option>
                        </Select>
                    </FormItem>
                </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
                <Col span="23">
                <FormItem label="" prop="selfCheckItems">
                    <b>自查存在的问题：</b>
                    <div class="fixed aR" style='margin-top: -30px;'>
                        <Button class="" :disabled="!dataClone.belongOrgId||dataClone.industryName.length<1" size='small' @click="addRowStandard('selfCheckItems')">刷新</Button>
                    </div>
                </FormItem>
                    <Table :columns="problemColumns" :data="dataClone.selfCheckItems" style="margin-bottom: 10px" :content="self">
                        <template slot-scope="{ row, index }" slot="ifInvolved">
                            <div v-if="!row.score && row.project !=='加分项'&&row.project !=='扣分项'"></div>
                            <i-switch :value="true" v-else v-model="dataClone.selfCheckItems[index].ifInvolved">
                                <span slot="open">{{ row.project ==='加分项'||row.project ==='扣分项'?0:row.score }}</span>
                                <span slot="close">0</span>
                            </i-switch>
                        </template>
                        <template slot-scope="{ row, index }" slot="problem">
                            <Input type="textarea" :autosize="{minRows:2,maxRows:5}" v-model="dataClone.selfCheckItems[index].problem" />
                        </template>
                        <template slot-scope="{ row, index }" slot="ratingScore">
                            <div v-if="(!row.score &&row.project !=='加分项'&&row.project !=='扣分项') || !row.ifInvolved"></div>
                            <InputNumber v-else-if="row.project ==='加分项'" :min='0' v-model="dataClone.selfCheckItems[index].ratingScore"></InputNumber>
                            <InputNumber v-else-if="row.project ==='扣分项'" :max="0" v-model="dataClone.selfCheckItems[index].ratingScore"></InputNumber>
                            <InputNumber v-else :min='0' :disabled="!row.ifInvolved" :max="row.score" v-model="dataClone.selfCheckItems[index].ratingScore"></InputNumber>
                        </template>
                        <template slot-scope="{ row, index }" slot="rectificationDetail">
                            <Input type="textarea" :autosize="{minRows:2,maxRows:5}" v-model="dataClone.selfCheckItems[index].rectificationDetail" />
                        </template>
                        <template slot-scope="{ row, index }" slot="action">
                            <!--<Button shape="circle" size="small" icon="md-close" @click="removeRowStandard('selfCheckItems', index)"></Button>-->
                            <Button size="small" type="primary" :disabled="!row.ifInvolved"
                                    @click="viewPicture(row.id);itemModel =true;questionItem = {...row};questionItem.index = index">评价</Button>
                        </template>
                    </Table>
                </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
                <Col span="11">
                <FormItem label="是否存在否决项：" prop="hasVeto1">
                    <Radio-group v-model.sync="dataClone.hasVeto1" @on-change="cleanVetoContent">
                        <Radio label="1">是</Radio>
                        <Radio label="0">否</Radio>
                    </Radio-group>
                </FormItem>
                </Col>
                <Col span="11">
                    <FormItem label="标准分：" prop="standardScore">
                        <InputNumber class="w" v-model='dataClone.standardScore' :min="0" readonly></InputNumber>
                    </FormItem>
                </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
                <Col span="23">
                <FormItem label="否决项内容：" prop="vetoContent1" v-if="dataClone.hasVeto1==1">
                    <Input type="text" v-model="dataClone.vetoContent1" placeholder="请输入否决项" />
                </FormItem>
                <!--<FormItem label="综合评定意见：" prop="score"></FormItem>-->
                </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
                <Col span="11">
                <FormItem label="评定得分：" prop="evaluationScore1">
                    <InputNumber class="w" v-model='evaluationScore1' :min="0" readonly></InputNumber>
                </FormItem>
                </Col>
                <Col span="11">
                <FormItem label="涉及得分：" prop="involvedScore1">
                    <InputNumber class="w" v-model='dataClone.involvedScore1' :min="0" readonly></InputNumber>
                </FormItem>
                </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
                <Col span="11">
                <FormItem label="综合评定得分：" prop="integretedScore1">
                    <InputNumber class="w" v-model='dataClone.integretedScore1' readonly :min="0"></InputNumber>
                </FormItem>
                </Col>
                <Col span="11">
                <FormItem label="评定等级：" prop="level1">
                    <Select class='w' v-model="dataClone.level1" :disabled="true">
                        <Option v-for="item in enStdMap" :value="item.codingCodeId" :key="item.codingCodeId">{{ item.codingName }}
                        </Option>
                    </Select>
                </FormItem>
                </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
                <Col span="11">
                    <FormItem label='填报人：' prop='selfLevelReport'>
                        <!--<div v-if="mode === 'view'">{{dataClone.selfLevelReport}}</div>-->
                        <Input type='text' v-model='dataClone.selfLevelReport' readonly></Input>
                    </FormItem>
                </Col>
                <Col span="11">
                    <FormItem label='手机号：' prop='selfLevelTelphone'>
                        <Input  type='text' v-model='dataClone.selfLevelTelphone'></Input>
                    </FormItem>
                </Col>
            </Row>
        </Form>
        <Modal title="选择标准" :transfer=false v-model="selectDialogShow" v-if="selectDialogShow" :width=1000
               :styles="{height:'726px'}"
               class-name='limit-height-dialog'>
            <select-item-table
                    ref="selectItemTable"
                    :dialogResourceSelectedDataArr="[]"
                    :dialogResourceSearchParams="{curCompanyId:currentUser.companyId}"
                    :dialogResourceSearchFormItems="dialogResourceSearchFormItems"
                    :dialogResourceQueryUrl="dialogResourceQueryUrl"
                    :dialogResourceColumns="dialogResourceColumns"
                    dialogResourceTableDataKey="itemId"
            ></select-item-table>
            <div slot="footer">
                <Button class='ivu-btn-save' @click="selectItemTableSubmitBtnClickHandle">确定</Button>
                <Button class='ivu-btn-cancel' @click="selectDialogShow=false">关闭</Button>
            </div>
        </Modal>

        <Modal title="图片上传" :transfer=false footer-hide v-model="pictureModal" :width=600>
            <Form ref="dataForm" :label-width="100">
                <Row type="flex" justify="space-around" class="code-row-bg" style="margin-top: 10px">
                    <Col span="23">
                        <FormItem label="上传图片：">
                            <div class="demo-upload-list" v-for="item in uploadList" :key="item.id">
                                <img :src="item.url">
                                <div class="demo-upload-list-cover">
                                    <Icon type="ios-eye-outline" @click.native="handleView(item.name,item.url)"></Icon>
                                    <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
                                </div>
                            </div>
                            <Upload
                                    ref="upload"
                                    :show-upload-list="false"
                                    :format="['jpg','jpeg','png','gif']"
                                    accept="image/jpg, image/jpeg,image/png,image/gif,image/bmp"
                                    :max-size="1024"
                                    :before-upload="handleBeforeUpload"
                                    multiple
                                    type="drag"
                                    :action="upUrl"
                                    style="display: inline-block;width:58px;">
                                <div style="width: 58px;height:58px;line-height: 58px;">
                                    <Icon type="ios-camera" size="20"></Icon>
                                </div>
                            </Upload>
                            <Modal title="View Image" v-model="visible">
                                <img :src="viewUrl" v-if="visible" style="width: 100%">
                                <div slot="footer">
                                    <Button type="primary" class='ivu-btn-save'  @click="visible=false">关闭</Button>
                                </div>
                            </Modal>
                        </FormItem>
                    </Col>
                </Row>
            </Form>
        </Modal>

        <Modal :mask-closable="false" :transfer=false v-model="itemModel" :width=800 :styles="{height:'700px'}"
               title="问题评价" @on-cancel="itemModel=false,questionItem={}">
            <Row>
                <Col span="24">
                    <Form ref="itemForm" :class="'modal-form'" :show-message="false" :model="questionItem"
                          :rules="itemRuleCustom" label-position="top">
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23">
                                <FormItem label='评价内容：' prop='content'>
                                    <Input class='' type="textarea" :autosize="{minRows:2,maxRows:5}" disabled
                                           v-model='questionItem.content'></Input>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23">
                                <FormItem label='评分标准：' prop='standard'>
                                    <Input class='' type="textarea" :autosize="{minRows:2,maxRows:5}" disabled
                                           v-model='questionItem.standard'></Input>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label='评价项目：' prop='project'>
                                    <Input class='' type='text' disabled v-model='questionItem.project'></Input>
                                </FormItem>
                            </Col>
                            <Col span="5">
                                <FormItem label='分值：' prop='score'>
                                    <Input class='' type='text' disabled v-model='questionItem.score'></Input>
                                </FormItem>
                            </Col>
                            <Col span="5">
                                <FormItem label='涉及得分：' prop='ifInvolved'>
                                    <i-switch :value="true" v-model="questionItem.ifInvolved">
                                        <span slot="open">{{ questionItem.project ==='加分项'||questionItem.project ==='扣分项'?0:questionItem.score }}</span>
                                        <span slot="close">0</span>
                                    </i-switch>
                                </FormItem>
                            </Col>
                        </Row>
                        <div v-if="questionItem.ifInvolved">
                            <Row type="flex" justify="space-around" class="code-row-bg">
                                <Col span="11">
                                    <FormItem label='问题类别：' prop='problemCategory'>
                                        <Select v-model="questionItem.problemCategory" label-in-value
                                                @on-change='(val)=>{questionItem.problemCategory=val.value;questionItem.problemCategoryName=val.label;}'>
                                            <Option v-for="item in environmentProtectionList" :value="item.codingCodeId"
                                                    :key="item.codingCodeId">{{ item.codingName }}
                                            </Option>
                                        </Select>
                                    </FormItem>
                                </Col>
                                <Col span="11">
                                    <FormItem label='自评得分：' prop='ratingScore'>
                                        <div v-if="(!questionItem.score &&questionItem.project !=='加分项'&&questionItem.project !=='扣分项') || !questionItem.ifInvolved"></div>
                                        <InputNumber v-else-if="questionItem.project ==='加分项'" :min='0' v-model="questionItem.ratingScore"></InputNumber>
                                        <InputNumber v-else-if="questionItem.project ==='扣分项'" :max="0" v-model="questionItem.ratingScore"></InputNumber>
                                        <InputNumber v-else :min='0' :disabled="!questionItem.ifInvolved" :max="questionItem.score" v-model="questionItem.ratingScore"></InputNumber>
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row type="flex" justify="space-around" class="code-row-bg">
                                <Col span="23">
                                    <FormItem label='存在的问题：' prop='problem'>
                                        <Input class='' placeholder="请填写存在的问题" type="textarea"
                                               :autosize="{minRows:2,maxRows:5}" v-model='questionItem.problem'></Input>
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row type="flex" justify="space-around" class="code-row-bg">
                                <Col span="23">
                                    <FormItem label='整改情况：' prop='rectificationDetail'>
                                        <Input class='' placeholder="请填写整改情况" type="textarea"
                                               :autosize="{minRows:2,maxRows:5}" v-model='questionItem.rectificationDetail'></Input>
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row type="flex" justify="space-around" class="code-row-bg" style="margin-top: 10px">
                                <Col span="23">
                                    <FormItem label="上传图片：">
                                        <div class="demo-upload-list" v-for="item in uploadList" :key="item.id">
                                            <img :src="item.url">
                                            <div class="demo-upload-list-cover">
                                                <Icon type="ios-eye-outline"
                                                      @click.native="handleView(item.name,item.url)"></Icon>
                                                <Icon type="ios-trash-outline"
                                                      @click.native="handleRemove(item)"></Icon>
                                            </div>
                                        </div>
                                        <Upload
                                                :show-upload-list="false"
                                                :format="['jpg','jpeg','png','gif']"
                                                accept="image/jpg, image/jpeg,image/png,image/gif,image/bmp"
                                                :max-size="1024"
                                                :before-upload="handleBeforeUpload"
                                                multiple
                                                type="drag"
                                                :action="upUrl"
                                                style="display: inline-block;width:58px;">
                                            <div style="width: 58px;height:58px;line-height: 58px;">
                                                <Icon type="ios-camera" size="20"></Icon>
                                            </div>
                                        </Upload>
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row type="flex" justify="space-around" class="code-row-bg">
                                <Col span="11">
                                    <FormItem label='检查时间：' prop='checkTime'>
                                        <DatePicker class="w" placeholder="请选择检查时间" v-model='questionItem.checkTime' :clearable="false"
                                                    :options="{disabledDate(date) {return date && date.valueOf() > new Date();}}"></DatePicker>
                                    </FormItem>
                                </Col>
                                <Col span="11">
                                    <FormItem label='完成时限：' prop='completeTime'>
                                        <DatePicker class="w" placeholder="请选择完成时限" v-model='questionItem.completeTime' :clearable="false"
                                                    :options="{disabledDate(date) {return date &&
                                                    questionItem.checkTime && date.valueOf() < questionItem.checkTime;}}"></DatePicker>
                                    </FormItem>
                                </Col>
                                <Col span="23">
                                    <Alert type="warning">{{this.Common.questionWarn}}</Alert>
                                </Col>
                            </Row>
                        </div>
                    </Form>
                </Col>
            </Row>
            <div slot="footer">
                <Button type="primary" class='ivu-btn-save' @click="saveOne(questionItem, questionItem.index,'selfCheckItems')">确定</Button>
                <Button type="primary" class='ivu-btn-cancel' @click="itemModel=false,questionItem={}">取消</Button>
                <!--<Button v-if="mode === 'view'" class='ivu-btn-save' @click="dialogShow=false">关闭</Button>-->
            </div>
        </Modal>

    </Row>
</template>

<script>
    import {Api} from "@/api";
    import {sessionStorage} from '@/common/cacheUtils.js';
    var cascaderDom = () => import('@/components/cascader-dom.vue');
    import _deepclone from 'lodash/cloneDeep'
    import SelectItemTable from "@/components/SelectItemTable.vue"
    import pageCommonFunction from '@/components/pageCommonFunction.js'
    import userDom from "@/components/input-user.vue";
    function countLevel(newVal) {
        let map = this.enStdMap
        let level = 1
        let score = this.dataClone.integretedScore1
        if (370 > score || this.dataClone.hasVeto1 == 1 ) {
            level = 4
        } else if (score >= 470) {
            level = 1
        } else if (470 > score && score >= 420) {
            level = 2
        } else if (420 > score && score >= 370) {
            level = 3
        }
        this.$set(this.dataClone, 'level1', map[level].codingCodeId)
    }

    export default {
        name: "self-check-form",
        props: ['data', 'enStdMap', 'mode','sending'],
        data() {
            return {
                dataClone: {},
                self: this,
                problemColumns: [
                    {title: '序号', key: 'seqNo', align: 'center', width: 60},
                    {title: '评价项目', key: 'project', align: 'center', width: 90},
                    {title: '评价内容', key: 'content', align: 'center', width: 110,tooltip:true },
                    {title: '评分标准', key: 'standard', align: 'center', width: 110,tooltip:true },
                    {title: '分值', key: 'score', width: 60, align: 'center'},
                    {title: '涉及得分', key: 'ifInvolved',slot: 'ifInvolved', width: 70, align: 'center'},
                    {title: '存在的问题', key: 'problem',minWidth: 110, tooltip:true, align: 'center'},
                    {title: '问题类别', key: 'problemCategoryName', width: 90, align: 'center',},
                    {title: '检查时间', key: 'checkTime', width: 100, align: 'center', render: this.renderCellDate},
                    {title: '完成时限', key: 'completeTime', width: 100, align: 'center', render: this.renderCellDate},
                    // {title: '自评得分', key: 'ratingScore', width: 100, align: 'center', slot: 'ratingScore'},
                    {
                        title: '自评得分', key: 'ratingScore', width: 60, align: 'center',
                        render: (h, params) => {
                            return h('span', [(!params.row.score && params.row.project !== '加分项' && params.row.project !== '扣分项') || !params.row.ifInvolved ? '' : params.row.ratingScore])
                        }
                    },
                    {title: '整改情况', key: 'rectificationDetail',minWidth: 110, align: 'center', tooltip:true},
                    {
                        width: 60,
                        title: '照片',
                        key: 'img',
                        align: 'center',
                        slot:'img',
                        render: (h, { row, index }) => {
                            return h("icon", {
                                props: {
                                    type: 'md-eye',
                                    size: '20'
                                },
                                style: {
                                    cursor: 'pointer'
                                },
                                on: {
                                    click: () => {
                                        this.pictureModal=true
                                        this.viewPicture(row.id);
                                    }
                                }
                            });
                        }
                    },
                    {title: '评定扣分', key: 'deductScore', width: 60, align: 'center', slot: 'deductScore',
                        render:(h, params)=>{
                            return h('span', [
                                ((!params.row.score || !params.row.ifInvolved)&&params.row.project !== '加分项'&& params.row.project !== '扣分项'? ''
                                    : (params.row.project === '加分项'|| params.row.project === '扣分项')? Math.abs(params.row.ratingScore)
                                        :(params.row.ratingScore === 0 ? params.row.score : (params.row.score===params.row.ratingScore?0:params.row.score-params.row.ratingScore)))
                            ]);
                        }},
                    {title: '操作', key: 'action', align: 'center', width: 65, slot: 'action'}
                ],
                ruleCustom: {
                    companyId: [{required: true, message: '请选择企业名称', trigger: 'blur'}],
                    selfLevelTime: [{required: true, message: '请选择自评时间', trigger: 'blur',type: 'date'}],
                    manager: [{required: true, message: '请选择企业负责人', trigger: 'blur'}],
                    industryName: [{
                        validator: (rule, value, callback) => {
                            if(value.length<1){
                                callback(' ');
                            } else {
                                callback()
                            }
                        },
                        required: true,
                        trigger: 'change'
                    }],
                    selfLevelTelphone: [{
                        validator: (rule, value, callback) => {
                            if(!(/^1[3456789]\d{9}$/.test(this.dataClone.selfLevelTelphone))){
                                callback(' ');
                            } else {
                                callback()
                            }
                        },
                        required: true,
                        trigger: 'blur'
                    }],
                    // selfCheckItems: [{
                    //     validator: (rule, value, callback) => {
                    //         for (let i = 0, il = dataClone.selfCheckItems.length; i < il; i++) {
                    //             let obj = dataClone.selfCheckItems[i]
                    //             if (!obj.score) {
                    //                 if (obj.problem === '' || obj.itemId === '' ) {//|| obj.rectificationDetail === ''
                    //                     callback(new Error('请填写自查问题表单中的每一项'));
                    //                     return
                    //                 }
                    //             }else {
                    //                 if (obj.ifInvolved && obj.deductScore>0 && (obj.problem === '' || obj.itemId === '' || obj.ratingScore === '')) {  //|| obj.rectificationDetail === ''
                    //                     callback(new Error('请填写自查问题表单中的每一项'));
                    //                     return
                    //                 }
                    //             }
                    //         }
                    //         callback();
                    //     }, trigger: 'blue'
                    // }],
                    hasVeto1: [{required: true, message: '请选择是否存在否决项', trigger: 'change'}],
                    vetoContent1: [{required: true, message: '请输入否决项', trigger: 'change'}],
                    evaluationScore1: [{pattern: /(\d+(\.\d+)?)/, message: '评定得分必须为数字', trigger: 'change'}],
                    involvedScore1: [{pattern: /(\d+(\.\d+)?)/, message: '涉及得分必须为数字', trigger: 'change'}],
                    integretedScore1: [{pattern: /(\d+(\.\d+)?)/, message: '综合评定得分必须为数字', trigger: 'change'}],
                    level1: [{required: true, message: '请输入评定等级', trigger: 'blur'}]
                },
                itemModel: false,
                questionItem: {},
                itemRuleCustom: {
                    problemCategory: [{required: true, message: '请选择问题类别', trigger: 'change'}],
                    problem: [{required: true, message: '请填写存在的问题', trigger: 'change'}],
                    checkTime: [{required: true, message: '请选择检查时间', trigger: 'change', type: 'date'}],
                    completeTime: [{required: true, message: '请选择完成时限', trigger: 'change', type: 'date'}],
                    rectificationDetail: [{required: true, message: '请选择整改情况', trigger: 'change',}],
                },
                sending: false,
                formLoading: false,
                // 選擇標準彈出框//
                dialogResourceType: '', // 类型
                selectDialogShow: false,
                dialogResourceSearchFormItems: [
                    {type: 'input', prop: 'project', label: '评价项目'},
                    {type: 'input', prop: 'content', label: '评价内容'},
                    {type: 'input', prop: 'standard', label: '评分标准'},
                    {type: 'input', prop: 'industryName', label: '行业分类'}
                ],
                dialogResourceQueryUrl: Api.queryEnStdStandard,
                dialogResourceColumns: [
                    {
                        align: 'center', type: 'selection', width: 60, filterMultiple: (row) => {
                            console.log(1 + row);
                            return true
                        }
                    },
                    {title: '行业分类', width: 130, align: 'center', key: 'industryId',
                        render:(h, params)=>{ return this.renderCellCode(h, params.row.industryId, 'env-00006');}},
                    {title: '评价项目', width: 130, align: 'center', key: 'project',},
                    {title: '评价内容', align: 'left', key: 'content',},
                    {title: '分值', width: 80, align: 'center', key: 'score',},
                    {title: '评分标准', align: 'left', key: 'standard',},
                ],

                industryNames:[],
                environmentProtectionList:[],
                uploadList: [],
                upUrl:Api.uploadPTWFiles,
                viewUrl : Api.interestedPartiesUserFile,
                visible:false,
                imgName: '',
                pictureModal:false,
                id:null,
                twoLevel:[],
                setCurrentUserName:{}
            }
        },
        watch: {
            'dataClone.hasVeto1': countLevel,
            'dataClone.integretedScore1': countLevel,
        },
        created() {
            if (this.mode === 'add') {
                this.dataClone = {
                    year: new Date().getFullYear().toString(),
                    auditTime: new Date(),
                    selfLevelTime: new Date(),
                    hasVeto1: '0',
                    industryName: [],
                    selfCheckItems: [],
                    sceneCheckItems: [],
                    evaluationScore1: 0,
                    involvedScore1: 0,
                    integretedScore1: 0,
                    standardScore:0,
                    belongOrgId :this.currentUser.twoLevelOrgId,
                    belongOrgName:this.currentUser.twoLevelOrgName,
                    companyId: JSON.parse(sessionStorage('userId').get('userId')).companyId,
                    companyName: JSON.parse(sessionStorage('userId').get('userId')).companyName,
                    selfLevelTelphone:JSON.parse(sessionStorage('userId').get('userId')).mobileNumber,
                    selfLevelReport:JSON.parse(sessionStorage('userId').get('userId')).userName,
                    // managerName:JSON.parse(sessionStorage('userId').get('userId')).userName,
                    // manager:JSON.parse(sessionStorage('userId').get('userId')).userId,
                    levelType:1  //1 自评， 2现场评价
                }
                // this.setCurrentUserName = { name: this.currentUser.userName};
                console.log(this.dataClone);
                this.industryNameArr(this.currentUser.twoLevelOrgId,this.dataClone.year)
            } else {
                let dataClone = _deepclone(this.data)
                if (!(dataClone.selfCheckItems instanceof Array)) {
                    dataClone.selfCheckItems = []
                }
                if (!(dataClone.sceneCheckItems instanceof Array)) {
                    dataClone.sceneCheckItems = []
                }
                dataClone.evaluationScore1 = (dataClone.evaluationScore1 !== undefined) ? dataClone.evaluationScore1 : ''
                dataClone.involvedScore1 = (dataClone.involvedScore1 !== undefined) ? dataClone.involvedScore1 : ''
                dataClone.integretedScore1 = (dataClone.integretedScore1 !== undefined) ? dataClone.integretedScore1 : ''
                dataClone.industryName = dataClone.industryId.split(',')
                this.dataClone = dataClone
                this.setCurrentUserName = { name: this.dataClone.managerName};
                this.industryNameArr(dataClone.belongOrgId,dataClone.year)
            }
            window.dataClone = this.dataClone
        },
        mounted() {
            if (this.mode === 'edit') {
                this.$Spin.show()
                this.$http.get(Api.getEnvSelfCheck + this.data.id, {params: {}}).then((res) => {
                    if (res.data.status === 201) {
                        this.$Message.error(res.data.msg);
                    } else {
                        this.dataClone.selfCheckItems = res.data.data.selfCheckItems
                        this.dataClone.sceneCheckItems = res.data.data.sceneCheckItems
                    }
                    this.$Spin.hide()
                }).catch(e => {
                    this.$Message.error("自评台账详情数据获取失败")
                    this.$Spin.hide()
                })
            }
            this.$http.get(Api.queryCodeDetailBySortId + '/NOT-00006', {params: {}}).then((res) => {
                this.environmentProtectionList = res.data.data;
            });
            this.$http.get(Api.quqeryTwoOrgInfo).then(res => {
                this.twoLevel=res.data.data
            }).catch(e => {
            })
            this.$refs.userDom.setCurrentInfo();
        },
        computed: {
            currentUser() {
                return JSON.parse(sessionStorage('userId').get('userId'))
            },
            evaluationScore1(){
                let evaluationScore1 = 0 // 评定得分
                let involvedScore1 = 0 // 涉及得分
                for (let i = 0, il = dataClone.selfCheckItems.length; i < il; i++) {
                    let obj = dataClone.selfCheckItems[i]
                    if ((!obj.score || !obj.ifInvolved) && obj.project !=='加分项'&&obj.project !=='扣分项') {
                        if (!obj.ifInvolved) {
                            obj.problem = ''
                            obj.rectificationDetail = null
                        }
                        obj.deductScore = ''
                        obj.ratingScore = obj.score
                        evaluationScore1+=0
                    }else {
                        if (obj.project === '加分项' || obj.project === '扣分项') {
                            if (!obj.ifInvolved) {
                                // obj.problem = ''
                                // obj.rectificationDetail = ''
                                obj.deductScore = ''
                                obj.ratingScore = 0
                            }else {
                                obj.deductScore= Math.abs(obj.ratingScore)
                            }
                            evaluationScore1+=obj.ratingScore
                            // involvedScore1 += obj.ratingScore
                        }else {
                            evaluationScore1+=obj.ratingScore
                            involvedScore1 += obj.score
                            obj.deductScore=obj.score- obj.ratingScore
                        }
                    }
                }
                this.dataClone.evaluationScore1=evaluationScore1
                this.dataClone.involvedScore1 = involvedScore1
                this.dataClone.integretedScore1=involvedScore1===0?0:(evaluationScore1/involvedScore1*500).toFixed(2)
                return evaluationScore1
            }
        },
        methods: {
            ...pageCommonFunction,
            // 点击取消。发出关闭弹出框事件
            handleCancel() {
                this.$emit('close-dialog')
            },
            // 发出保存成功事件
            handleSaveSuccess() {
                this.$emit('save-success')
            },
            // 清空否决项
            cleanVetoContent(value) {
                if (value == 0) {
                    this.dataClone.vetoContent1 = ' ';
                }
            },
            industryNameArr(twoLevelOrgId,year){
                this.$http.get(Api.queryIndustryName, {params: {belongOrgId:twoLevelOrgId}}).then((res) => {
                    this.industryNames = res.data.data.filter(m=>m['year']==year).map(m=>m['industryName']);
                });
            },
            belongChange(value) {
                this.dataClone.belongOrgId = value.value
                this.dataClone.belongOrgName = value.label
                this.dataClone.companyId = null
                this.dataClone.industryName = []
                this.dataClone.selfCheckItems = []
                this.$refs.companyQuery.resetCurrentOrg();
                this.industryNameArr(value.value,this.dataClone.year)
            },
            // 一行自评相关操作
            addRowStandard(type) {
                /*this.dialogResourceType = type;
                console.log(this.currentUser)
                this.selectDialogShow = true*/
                this.formLoading = true
                let data = {
                    startPage: 0,
                    size: 0,
                    curCompanyId: this.dataClone.companyId,
                    industryName:this.dataClone.industryName.join(','),
                    belongOrgId:this.dataClone.belongOrgId,
                    year: this.dataClone.year
                };
                this.$http.get(this.dialogResourceQueryUrl, {params: data}).then((res) => {
                    if (res.data.status === 201) {
                        this.$Message.error(res.data.msg);
                    }
                    this.dataClone[type]=[]
                    let involvedScore1=0
                    res.data.data.data.forEach(item => {
                        this.dataClone[type].push({
                            ...item,
                            // project standard
                            ifInvolved: true,
                            id:this.get_uuid(),
                            problem: item.score ?'':'无',
                            ratingScore: item.project === '加分项' || item.project === '扣分项'? 0: item.score,
                            rectificationDetail: null,
                            deductScore: '',
                        })
                        if (item.score) {
                            involvedScore1+=item.score
                        }else {
                            involvedScore1+=0
                        }
                    })
                    this.dataClone.evaluationScore1=involvedScore1
                    this.dataClone.involvedScore1=involvedScore1
                    this.dataClone.standardScore=involvedScore1
                    if (res.data.data.data.length < 1) {
                        this.$Message.error("集团尚未维护生态环境标准化指标\n")
                    }
                    this.formLoading = false
                }).catch(e => {
                    this.formLoading = false
                    this.$Message.error("数据获取失败")
                })
            },
            selectItemTableSubmitBtnClickHandle() {
                this.selectDialogShow = false
                var selectedArr = this.$refs.selectItemTable.getSelectedDataArr()
                selectedArr.forEach(item => {
                    this.dataClone[this.dialogResourceType].push({
                        ...item,
                        // project standard
                        problem: '',
                        ratingScore: item.score,
                        rectificationDetail: undefined,
                        deductScore: '',
                    })
                })

            },
            removeRowStandard(type, index) {
                this.dataClone.involvedScore1=this.dataClone.involvedScore1-0-this.dataClone[type][index].score
                this.dataClone[type].splice(index, 1)
                // this.$refs['selfCheckForm'].validateField(type)
            },
            saveOne(row, index, type) {
                this.$refs['itemForm'].validate((valid) => {
                    if (valid) {
                        this.$Modal.confirm({
                            title: '提示',
                            content: '<p>是否要提交？</p>',
                            onOk: () => {
                                row.createUserId = this.currentUser.userId
                                row.createOrgId = this.currentUser.orgId
                                row.companyId = this.dataClone.companyId
                                row.belongOrgId = this.dataClone.belongOrgId
                                // row.businessId = row.id
                                row.priBusinessId = this.dataClone.id
                                // this.$http.post(Api.updateEnvSelfCheckItem, row).then((res) => {
                                //     if (res.data.status === 200) {
                                this.$Message.info('保存成功')
                                row.createUserName = this.currentUser.userName
                                this.dataClone[type][index].createUserName = this.currentUser.userName
                                this.dataClone[type][index].problemCategory = row.problemCategory
                                this.dataClone[type][index].problemCategoryName = row.problemCategoryName
                                this.dataClone[type][index].ratingScore = row.ratingScore
                                this.dataClone[type][index].problem = row.problem
                                this.dataClone[type][index].problemDesc = row.problem
                                this.dataClone[type][index].checkTime = row.checkTime
                                this.dataClone[type][index].completeTime = row.completeTime
                                this.dataClone[type][index].rectificationDetail = row.rectificationDetail
                                this.dataClone[type][index].ifInvolved = row.ifInvolved
                                    // } else if (res.data.status === 201) {
                                    //     this.$Message.error(res.data.msg);
                                    // }
                                    this.itemModel=false
                                    this.questionItem={}
                                // }).catch(e => {
                                //     this.$Message.error("保存异常");
                                // })
                            },
                            onCancel: () => {}
                        })
                    }else {
                        this.$Message.error('请填报完整!');
                    }
                })
            },
            // 提交
            submit(name) {
                if (this.sending) return
                if (this.dataClone.selfCheckItems.length < 1) {
                    this.$Message.error("自查存在的问题至少一条！")
                    return
                }
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        let url = Api.updateEnvSelfCheck
                        if (this.mode === 'add') {
                            url = Api.saveEnvSelfCheck
                        }
                        this.sending = true
                        this.$emit('sending',true)
                        this.dataClone.levelType='1'
                        this.dataClone.industryId = this.dataClone.industryName.join(',') //split
                        this.$http.post(url, this.dataClone).then((res) => {
                            if (res.data.status === 200) {
                                this.$Message.success(this.mode === 'add' ? '添加成功' : '编辑成功');
                                this.handleSaveSuccess()
                            } else if (res.data.status === 201) {
                                this.$Message.error(res.data.msg);
                            }
                            this.sending = false
                            this.$emit('sending',false)
                        }).catch(e => {
                            this.$Message.error("提交失败")
                            this.sending = false
                            this.$emit('sending',false)
                        })
                    } else {
                        this.$Message.error('请填报完整!');
                    }
                })
            },
            viewPicture(id){
                this.uploadList = [];
                this.id=id
                let url=this.viewUrl +  '/' + id + '/files/picture'
                this.$http.get(url + "?field=selfChecke").then((res) => {
                    if (res.data.result == "success") {
                        console.log(res.data)
                        res.data.data.map((item)=>{
                            this.uploadList.push({ name : item.fileName, id : item.id , url : Api.downloadPTWSchemeFile + '/' + item.id});
                        });
                    }
                })
            },
            handleView (name,url) {
                this.viewUrl = url;
                this.imgName = name;
                this.visible = true;
            },
            handleRemove(item) {
                console.log(item)
                let url = this.viewUrl + '/file/' + item.id;
                this.$http.delete(url).then((res) => {
                    this.viewPicture(this.id)
                })
            },
            handleBeforeUpload (file) {
                if(file.size > 1024*1024){
                    this.$Message.error('图片不能大于1M.');
                    return false;
                }
                let index = file.name.lastIndexOf(".");
                let suffix = file.name.substr(index+1).toLowerCase();
                if(suffix!='jpg' && suffix!='jpeg' && suffix!='png'&& suffix!='gif'){
                    this.$Message.error("请上传jpg,jpeg,png,gif格式的图片");
                    return false;
                }
                let check = this.uploadList.length < 9;
                if (!check) {
                    this.$Message.error('最多上传9张图片');
                    return false;
                }
                let formData = new FormData();
                formData.append("files", file);
                this.$http.post(this.viewUrl +  '/' + this.id + '/files/picture/selfChecke', formData).then((res) => {
                    if (res.data.result == "success") {
                        this.$Message.success("上传成功");
                        this.viewPicture(this.id)
                    } else {
                        this.$Message.error("附件上传失败");
                    }
                }).catch(e => {
                    console.log(e);
                    this.$Message.error("数据获取失败");
                })
                return false;
            },
        },
        components: {
            cascaderDom,
            SelectItemTable,
            userDom
        },
    }
</script>

<style scoped>
    .mb10 {
        margin-bottom: 10px;
    }

    .aR {
        text-align: right;
    }

    .fixed:after {
        display: block;
        content: '';
        clear: both;
        width: 100%;
        height: 0;
    }

    .self-check-form {
    }

    /deep/ .self-check-form .ivu-form-item {
        /*margin-bottom: 24px;*/
    }

    /deep/ .self-check-form .ivu-table-wrapper {
        overflow: visible;
    }

    /deep/ .self-check-form .ivu-table-wrapper .ivu-table {
        overflow: visible;
    }
    .demo-upload-list{
        display: inline-block;
        width: 60px;
        height: 60px;
        text-align: center;
        line-height: 60px;
        border: 1px solid transparent;
        border-radius: 4px;
        overflow: hidden;
        background: #fff;
        position: relative;
        box-shadow: 0 1px 1px rgba(0,0,0,.2);
        margin-right: 4px;
    }
    .demo-upload-list img{
        width: 100%;
        height: 100%;
    }
    .demo-upload-list-cover{
        display: none;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background: rgba(0,0,0,.6);
    }
    .demo-upload-list:hover .demo-upload-list-cover{
        display: block;
    }
    .demo-upload-list-cover i{
        color: #fff;
        font-size: 20px;
        cursor: pointer;
        margin: 0 2px;
    }
</style>
